<?php

declare(strict_types=1);
/**
 * Author: Zane
 * Email: 873934580@qq.com
 * Date: 2023/5/30.
 */

namespace App\Service;

use App\Models\Permission;
use Illuminate\Support\Facades\Auth;

class PermissionService
{
    /**
     * @return array
     */
    public function getLabel(): array
    {
        return Permission::query()
            ->select(['id', 'name', 'title', 'parent_id'])
            ->orderBy('weight', 'desc')->get()->toArray();
    }

    public function myPermission(): array
    {
        $member = Auth::guard(config('auth.app_guard_name'))->user();
        $results = [];
        // 当用户为创始人时直接返回全部权限
        if ($member->is_founder) {
            $results = Permission::query()
                ->select(['id', 'parent_id', 'name', 'title', 'route', 'component', 'icon', 'type', 'status', 'is_nav'])
                ->orderBy('weight', 'desc')
                ->orderBy('id', 'asc')
                ->get()->toArray();
        } else {
            foreach ($member->roles()->get() as $item) {
                $permissions = $item->permissions()->orderBy('weight', 'desc')->orderBy('id', 'asc')->get()->toArray();
                foreach ($permissions as $value) {
                    if ($value['deleted_at']) {
                        continue;
                    }
                    if (isset($results[$value['id']])) {
                        continue;
                    }
                    $results[$value['id']] = $value;
                }
            }
        }

        return infiniteTree($results);
    }
}
